import 'package:flutter/material.dart';

import 'MyBottomDialog.dart';

/// 弹窗动画类型
// enum DialogAnimationType {
//   slide,
//   popup,
// }

class MyBottomDialog2 {
  /// 显示自定义 Dialog
  static Future<void> show({
    required BuildContext context,
    required Widget Function(BuildContext) builder,
    required double height,
    double? dialogWidth, // ✅ 新增宽度参数
    double borderRadius = 16,
    bool barrierDismissible = true,
    DialogAnimationType animationType = DialogAnimationType.popup,
    bool avoidSoftInput = true, // ✅ 是否自动避开键盘
  }) {
    return showGeneralDialog(
      context: context,
      barrierDismissible: barrierDismissible,
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
      barrierColor: Colors.black54,
      transitionDuration: const Duration(milliseconds: 300),
      pageBuilder: (_, __, ___) => const SizedBox.shrink(),
      transitionBuilder: (context, animation, secondaryAnimation, _) {
        final curved = CurvedAnimation(
          parent: animation,
          curve: Curves.easeOutCubic,
        );

        final mediaQuery = MediaQuery.of(context);
        final bottomInset = mediaQuery.viewInsets.bottom;

        // 默认宽度为 85% 屏宽
        final double dialogW = dialogWidth ?? mediaQuery.size.width * 0.85;

        // 让弹窗不受父页面键盘影响
        Widget dialog = MediaQuery.removeViewInsets(
          removeBottom: !avoidSoftInput,
          context: context,
          child: Center(
            child: ConstrainedBox(
              constraints: BoxConstraints(
                maxWidth: dialogW,
                maxHeight: mediaQuery.size.height * 0.9,
              ),
              child: Material(
                color: Colors.white,
                borderRadius: BorderRadius.circular(borderRadius),
                child: SizedBox(
                  height: height,
                  width: dialogW,
                  child: builder(context),
                ),
              ),
            ),
          ),
        );

        if (avoidSoftInput) {
          dialog = Padding(
            padding: EdgeInsets.only(bottom: bottomInset),
            child: dialog,
          );
        }

        // 动画
        switch (animationType) {
          case DialogAnimationType.slide:
            return SlideTransition(
              position: Tween<Offset>(
                begin: const Offset(0, 1),
                end: Offset.zero,
              ).animate(curved),
              child: dialog,
            );
          case DialogAnimationType.popup:
          default:
            return ScaleTransition(
              scale: curved,
              child: dialog,
            );
        }
      },
    );
  }
}
